package cn.tedu.ivos.base.aspect;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Aspect
@Component
public class RequestLog {

    private final static Logger logger = LoggerFactory.getLogger(RequestLog.class);

    @Pointcut("execution(public * cn.tedu.ivos.*.controller..*.*(..))")
    public void anyController() {
    }


    @Before("anyController()")
    public void before(JoinPoint joinPoint) {
        // 请求URL
        requestUrl();
        // 请求参数
        Object[] args = joinPoint.getArgs();
        Stream<?> stream = ArrayUtils.isEmpty(args) ? Stream.empty() : Arrays.stream(args);
        List<Object> logArgs = stream
                .filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse) &&
                        !(arg instanceof MultipartFile)))
                .collect(Collectors.toList());
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        // 类路径URL
        String methodPackage = methodSignature.getDeclaringTypeName();
        // 方法名
        String method = methodSignature.getMethod().getName();
        String builder = methodPackage +
                "." +
                method +
                "，请求参数：" +
                JSON.toJSONString(logArgs);
        logger.info(builder);
    }

    /**
     * 打印请求URL
     */
    private void requestUrl() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            String requestUrl = request.getRequestURI();
            logger.info(String.format("请求URL：%s", requestUrl));
        }
    }

}

